package com.lungle.warmdiary.app.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.AppManager;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.interf.ICallbackResult;
import com.lungle.warmdiary.app.model.SimpleBackPage;
import com.lungle.warmdiary.app.model.response.Active;
import com.lungle.warmdiary.app.model.response.AlipayAccount;
import com.lungle.warmdiary.app.model.response.CampaignComment;
import com.lungle.warmdiary.app.model.response.CampaignMycomment;
import com.lungle.warmdiary.app.model.response.Comment;
import com.lungle.warmdiary.app.model.response.MediaAccount;
import com.lungle.warmdiary.app.model.response.Tag;
import com.lungle.warmdiary.app.model.response.TesterStat;
import com.lungle.warmdiary.app.model.response.TradeRecoder;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.model.response.WithdrawRecoder;
import com.lungle.warmdiary.app.service.DownloadService;
import com.lungle.warmdiary.app.ui.dialog.CommonDialog;
import com.lungle.warmdiary.app.view.MainActivity;
import com.lungle.warmdiary.app.view.active.ActiveTab;
import com.lungle.warmdiary.app.view.common.ActiveDetailActivity;
import com.lungle.warmdiary.app.view.common.DetailActivity;
import com.lungle.warmdiary.app.view.common.SimpleBackActivity;
import com.lungle.warmdiary.app.view.me.LoginActivity;
import com.lungle.warmdiary.app.view.me.PwdResetActivity;
import com.lungle.warmdiary.app.view.me.fragment.MediaAddResultFragment;
import com.lungle.warmdiary.app.view.message.fragment.MessageDetailFragment;
import com.lungle.warmdiary.app.view.settings.fragment.BrowserFragment;
import com.lungle.warmdiary.app.view.wallet.fragment.AccountCenterFragment;
import com.lungle.warmdiary.app.view.wallet.fragment.TradeDetailFragment;
import com.lungle.warmdiary.app.view.wallet.fragment.WithdrawDetailFragment;

import java.io.Serializable;
import java.util.List;


@SuppressLint("SetJavaScriptEnabled")
public class UIHelper {
    /**
     * /media/campaign/detail?id=&mediaid=
     */
    private final static String PAGE_ACTIVE_DETAIL = "/media/campaign/detail";


    /**
     * 亲测活动 活动id
     * /media/test-campaign/detail?id=&
     */
    private final static String PAGE_TEST_CAMPAIGN = "/media/test-campaign/detail";


    /**
     * /media/campaign-process?status=我的活动页
     */
    private final static String PAGE_MY_ACTIVE = "/media/campaign-process";

    /**
     * media/withdraw  我的提现页
     */
    private final static String PAGE_WITHDRAW = " /media/withdraw";

    /**
     * media/withdraw/detail?id=  提现详情页
     */
    private final static String PAGE_WITHDRAW_DETAIL = "/media/withdraw/detail";

    /**
     * media/account/detail?id= 账号详情页
     */
    private final static String PAGE_ACCOOUNT_DETAIL = "/media/account/detail";


    public static void showActiveDetail(Context context, String activeId, String mediaid) {
        Intent intent = new Intent(context, ActiveDetailActivity.class);
        intent.putExtra("active_id", activeId);
        intent.putExtra("media_id", mediaid);
        intent.putExtra(ActiveDetailActivity.BUNDLE_KEY_PAGE, SimpleBackPage.ACTIVE_DETAIL.getValue());
        context.startActivity(intent);
    }

    public static void showActiveCommentDetail(Context context, Comment comment) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("Comment", comment);
        showSimpleBack(context, SimpleBackPage.ACTIVITY_COMMENT_DETAIL, bundle);
    }

    public static void showActiveCommentDetail(Context context, CampaignComment comment) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("CampaignComment", comment);
        showSimpleBack(context, SimpleBackPage.ACTIVITY_COMMENT_DETAIL2, bundle);
    }

    public static void showMyActiveList(Context context, int state, int num) {
        Bundle args = new Bundle();
        args.putInt("active_state", state);
        args.putInt("active_num", num);
        showSimpleBack(context, SimpleBackPage.MY_ACTIVE_LIST, args);
    }

    public static void showActiveList(Context context) {
        showSimpleBack(context, SimpleBackPage.ACTIVE_FORCE_LIST);
    }


    public static void showMessageDetail(Context context, com.lungle.warmdiary.app.model.response.Message message) {
        Intent intent = new Intent(context, DetailActivity.class);
        intent.putExtra(MessageDetailFragment.ARGS_MESSAGE, message);
        intent.putExtra(DetailActivity.BUNDLE_KEY_DISPLAY_TYPE,
                DetailActivity.DISPLAY_MESSAGE);
        context.startActivity(intent);
    }


    public static void showShareMore(Activity context, final String title,
                                     final String url) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享：" + title);
        intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
        context.startActivity(Intent.createChooser(intent, "选择分享"));
    }


    public static void showSimpleBackForResult(Fragment fragment,
                                               int requestCode, SimpleBackPage page, Bundle args) {
        Intent intent = new Intent(fragment.getActivity(),
                SimpleBackActivity.class);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE, page.getValue());
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_ARGS, args);
        fragment.startActivityForResult(intent, requestCode);
    }

    public static void showSimpleBackForResult(Activity context,
                                               int requestCode, SimpleBackPage page, Bundle args) {
        Intent intent = new Intent(context, SimpleBackActivity.class);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE, page.getValue());
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_ARGS, args);
        context.startActivityForResult(intent, requestCode);
    }

    public static void showSimpleBackForResult(Activity context,
                                               int requestCode, SimpleBackPage page) {
        Intent intent = new Intent(context, SimpleBackActivity.class);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE, page.getValue());
        context.startActivityForResult(intent, requestCode);
    }

    public static void showSimpleBack(Context context, SimpleBackPage page) {
        Intent intent = new Intent(context, SimpleBackActivity.class);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE, page.getValue());
        context.startActivity(intent);
    }

    public static void showSimpleBack(Context context, SimpleBackPage page,
                                      Bundle args) {
        Intent intent = new Intent(context, SimpleBackActivity.class);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_ARGS, args);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE, page.getValue());
        context.startActivity(intent);
    }


    public static void showMessage(Context context) {
        showSimpleBack(context, SimpleBackPage.MESSAGE);
    }

    public static void showWallet(Context context) {
        showSimpleBack(context, SimpleBackPage.WALLET);
    }

    public static void showTradeRecord(Context context) {
        showSimpleBack(context, SimpleBackPage.TRADE_RECORD);
    }

    public static void showTradeRecordDetail(Context context, TradeRecoder recoder) {
        Intent intent = new Intent(context, DetailActivity.class);
        intent.putExtra(TradeDetailFragment.ARGS_TRADE, recoder);
        intent.putExtra(DetailActivity.BUNDLE_KEY_DISPLAY_TYPE,
                DetailActivity.DISPLAY_TRADE);
        context.startActivity(intent);
    }

    public static void showTradeRecordDetail(Context context, String id) {
        Intent intent = new Intent(context, DetailActivity.class);
        intent.putExtra(TradeDetailFragment.ID_TRADE, id);
        intent.putExtra(DetailActivity.BUNDLE_KEY_DISPLAY_TYPE,
                DetailActivity.DISPLAY_TRADE);
        context.startActivity(intent);
    }


    public static void showWithdrawRecord(Context context) {
        showSimpleBack(context, SimpleBackPage.TAKECASH_RECORD);
    }

    public static void showWithdrawDetail(Context context, WithdrawRecoder recoder) {
        Intent intent = new Intent(context, DetailActivity.class);
        intent.putExtra(WithdrawDetailFragment.ARGS_TRADE, recoder);
        intent.putExtra(DetailActivity.BUNDLE_KEY_DISPLAY_TYPE,
                DetailActivity.DISPLAY_WITHDRAW);
        context.startActivity(intent);
    }


    public static void showWithdrawDetail(Context context, String id) {
        Intent intent = new Intent(context, DetailActivity.class);
        intent.putExtra(WithdrawDetailFragment.ID_TRADE, id);
        intent.putExtra(DetailActivity.BUNDLE_KEY_DISPLAY_TYPE, DetailActivity.DISPLAY_WITHDRAW);
        context.startActivity(intent);
    }

    public static void showWithdrawCenter(Context context, AlipayAccount alipay) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("alipay", alipay);
        showSimpleBack(context, SimpleBackPage.TAKECASH_CENTER, bundle);
    }


    public static void showUserInfo(Activity context) {
        // TODO: 2016/8/17  
    }


    public static void showMediaCenter(Context context) {
        Bundle args = new Bundle();
        showSimpleBack(context, SimpleBackPage.MEDIA_CENTER, args);

    }


    public static void showUserProfile(Activity activity, User user) {
        Bundle args = new Bundle();
        args.putSerializable("user", user);
        showSimpleBack(activity, SimpleBackPage.USERPROFILE_SETTING, args);
    }

    public static void showIconSelect(Fragment fragment, int requestCode, String path) {
        Bundle bundle = new Bundle();
        bundle.putString("icon_path", path);

        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.WECAHT_ICON_SELECT, bundle);

    }

    public static void showFriendNumSelect(Fragment fragment, int requestCode, String friendNum, String path) {
        Bundle bundle = new Bundle();
        bundle.putString("friend_num", friendNum);
        bundle.putString("friend_image_path", path);

        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.WECAHT_FRIENDS_SELECT, bundle);

    }

    public static void showWidChange(Fragment fragment, int requestCode, String wid, String path, boolean isEdit) {
        Bundle bundle = new Bundle();
        bundle.putString("wechat_name", wid);
        bundle.putString("weicat_name_screenshot", path);
        bundle.putBoolean("weichat_edit", isEdit);

        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.WECAHT_NAME_SELECT, bundle);

    }

    public static void showWechatNickname(Fragment fragment, int requestCode, String username) {
        Bundle bundle = new Bundle();
        bundle.putString("nickname", username);
        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.WECAHT_USERNAME_CHANGE, bundle);

    }


    public static void showMediaAddResult(Activity activity, MediaAccount account, int action) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("media_account", account);
        bundle.putInt("action", action);
        showSimpleBack(activity, SimpleBackPage.MEDIA_ACCOUNT_ADD_RESULT, bundle);
    }

    public static void showMeidaAdd(Activity activity) {
        Bundle args = new Bundle();
        showSimpleBack(activity, SimpleBackPage.MEDIA_ACCOUNT_ADD, args);


    }


    public static void showTags(Fragment fragment, int requestCode, int catlog, List<Tag> tags) {
        Bundle args = new Bundle();
        args.putInt("catalog", catlog);
        args.putSerializable("select_tags", (Serializable) tags);
        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.SELECT_TAG, args);
    }


    public static void openSysBrowser(Context context, String url) {
        try {
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        } catch (Exception e) {
            e.printStackTrace();
            AppContext.showToastShort("无法浏览此网页");
        }
    }


    public static void openBrowser(Context context, String title, String url) {
        Intent intent = new Intent(context, SimpleBackActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(BrowserFragment.BROWSER_KEY, url);
        bundle.putString(BrowserFragment.BROWSER_TITLE, title);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_ARGS, bundle);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE,
                SimpleBackPage.REGISTER_PROTOCOL.getValue());
        context.startActivity(intent);

    }

    public static void openBrowser(Context context, String url) {
        Intent intent = new Intent(context, SimpleBackActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(BrowserFragment.BROWSER_KEY, url);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_ARGS, bundle);
        intent.putExtra(SimpleBackActivity.BUNDLE_KEY_PAGE,
                SimpleBackPage.REGISTER_PROTOCOL.getValue());
        context.startActivity(intent);

    }

    public static TextWatcher getTextWatcher(final Activity context, final View view) {
        return new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                view.setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE : View.VISIBLE);
            }
        };
    }


    public static View.OnClickListener finish(final Activity activity) {
        return new View.OnClickListener() {
            public void onClick(View v) {
                activity.finish();
            }
        };
    }


    public static void showAbout(Context context) {
        showSimpleBack(context, SimpleBackPage.ABOUT);
    }


    public static void showBindAccount(Context context) {
        Bundle bundle = new Bundle();
        showSimpleBack(context, SimpleBackPage.ACCOUNT_BIND, bundle);
    }


    public static void showExecuteScreenshot(Fragment fragment, int requestCode, Active active) {
        Bundle args = new Bundle();
        args.putSerializable("active", active);
        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.EXCUTE_SCREENSHOT, args);
    }

    public static void showCommentScreenshot(Fragment fragment, int requestCode, Active active) {
        Bundle args = new Bundle();
        args.putSerializable("active", active);
        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.COMMENT_SCREENSHOT, args);
    }

    public static void showCommentDetailScreenshot(Fragment fragment, int requestCode, Active active) {
        Bundle args = new Bundle();
        args.putSerializable("active", active);
        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.COMMENT_DETAI_SCREENSHOT, args);
    }

    public static void showAccountCenter(Context context, AlipayAccount account) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(AccountCenterFragment.ARGS_ACCOUNT, account);
        showSimpleBack(context, SimpleBackPage.ACCOUNT_CENTER, bundle);
    }


    public static void loginOrLogout(Activity activity) {
        AppContext ac = (AppContext) activity.getApplication();
        if (ac.isLogin()) {
            ac.Logout();
            // ToastMessage(activity, "已退出登录");
            AppContext.showToastShort(R.string.tip_logout_success);
        } else {
            // showLoginDialog(activity);
            UIHelper.showLogin(activity);
        }
    }


    public static void clearAppCache(Activity activity) {
        final AppContext ac = (AppContext) activity.getApplication();
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AppContext.showToastShort("缓存清除成功");
                } else {
                    AppContext.showToastShort("缓存清除失败");
                }
            }
        };
        new Thread() {
            public void run() {
                Message msg = new Message();
                try {
                    ac.clearAppCache();
                    msg.what = 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = -1;
                }
                handler.sendMessage(msg);
            }
        }.start();
    }


    public static void showMain(Context context, int actionId) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(MainActivity.ACTION_KEY, actionId);
        context.startActivity(intent);
    }

    public static void showMainActiveStatus(Activity context, int statusId) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("active_status", statusId);
        context.startActivity(intent);
    }

    public static void showLogin(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(LoginActivity.BUNDLE_KEY_REQUEST_CODE, LoginActivity.REQUEST_CODE_RELOGIN);
        context.startActivity(intent);
    }

    public static void showChangePwd(Context context) {
        Intent intent = new Intent(context, PwdResetActivity.class);

        context.startActivity(intent);
    }

    public static void exitApp(Context context) {
        Intent intent = new Intent(BaseActivity.INTENT_ACTION_EXIT_APP);
        context.sendBroadcast(intent);
    }

    public static void showMsg(Context context, String msg) {
        CommonDialog dialog = new CommonDialog(context);
        dialog.setMessage(msg);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public static void sendAppCrashReport(final Context context, final String crashReport) {
        CommonDialog dialog = new CommonDialog(context);
        dialog.setTitle("小赶赶出错了");
        dialog.setMessage("非常抱歉，小赶赶无法工作了");
        dialog.setPositiveButton("提交报告", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                //发送问题
                AppManager.getAppManager().AppExit(context);

            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                AppManager.getAppManager().AppExit(context);

            }
        });


    }


    public static void openDownLoadService(Context context, String downurl,
                                           String tilte) {
        final ICallbackResult callback = new ICallbackResult() {

            @Override
            public void OnBackResult(Object s) {
            }
        };
        ServiceConnection conn = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
                binder.addCallback(callback);
                binder.start();

            }
        };
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(DownloadService.BUNDLE_KEY_DOWNLOAD_URL, downurl);
        intent.putExtra(DownloadService.BUNDLE_KEY_TITLE, tilte);
        context.startService(intent);
        context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }


    public static boolean dispatchAction(Context context, String path) {
        if (path.startsWith(PAGE_ACTIVE_DETAIL)) {
            try {
                String[] param = path.split("\\?");
                String id = param[1].split("&")[0].split("=")[1];
                String mediaid = param[1].split("&")[1].split("=")[1];
                showActiveDetail(context, id, mediaid);
            } catch (Exception e) {
                UIHelper.showMainActiveStatus((Activity) context, ActiveTab.UNLIMITED.getIdx());

//                showActiveList(context);
            }
            return true;

        } else if (path.startsWith(PAGE_ACCOOUNT_DETAIL)) {
            String id = path.split("\\?")[1].split("=")[1];
            MediaAccount mediaAccount = new MediaAccount();
            mediaAccount.setId(id);
            showMediaAddResult((Activity) context, mediaAccount, MediaAddResultFragment.ACTION_UPDATE);
            return true;
        } else if (path.startsWith(PAGE_MY_ACTIVE)) {
            String status = path.split("\\?")[1].split("=")[1];
            UIHelper.showMainActiveStatus((Activity) context, Integer.parseInt(status));

//            showMyActiveList(context, Integer.parseInt(status), 0);
            return true;
        } else if (path.startsWith(PAGE_WITHDRAW_DETAIL)) {
            String id = path.split("\\?")[1].split("=")[1];
            showTradeRecordDetail(context, id);
            return true;
        } else if (path.startsWith(PAGE_WITHDRAW)) {
            showWithdrawRecord(context);
            return true;
        } else if (path.startsWith(PAGE_TEST_CAMPAIGN)) {
            String id = path.split("\\?")[1].split("=")[1];
            showCampaignDetail(context, id);
            return true;
        }

        return false;
    }


    public static void showCampaignDetail(Context context, String campaignId, String icon, String title, int vendor) {
        Intent intent = new Intent(context, ActiveDetailActivity.class);
        intent.putExtra("campaignid", campaignId);
//        intent.putExtra("productid", produceId);
        intent.putExtra("icon", icon);
        intent.putExtra("title", title);
        intent.putExtra("rate", vendor);
        intent.putExtra(ActiveDetailActivity.BUNDLE_KEY_PAGE, SimpleBackPage.CAMPAIGNDETAIL.getValue());
        context.startActivity(intent);
    }

    public static void showCampaignComment(Context context, String campaignId, String produceId, String auduinfo, int action) {
        Bundle args = new Bundle();
        args.putString("campaignid", campaignId);
        args.putString("productid", produceId);
        args.putString("auditInfo", auduinfo);
        args.putInt("action", action);
        showSimpleBack(context, SimpleBackPage.CAMPAIGNCOMMENT, args);
    }

    public static void showCampaignComment(Context context, CampaignMycomment campaignMycomment, int action) {
        Bundle args = new Bundle();
        args.putSerializable("CampaignMycomment", campaignMycomment);
        args.putInt("action", action);
        showSimpleBack(context, SimpleBackPage.CAMPAIGNCOMMENT, args);
    }


    public static void showCampaignCommentDetail(Context context, CampaignComment campaignComment) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("campaignComment", campaignComment);
        showSimpleBack(context, SimpleBackPage.CAMPAIGNCOMMENT_DETAIL, bundle);
    }

    public static void showCampaignCommentDetail(Context context, CampaignMycomment campaignComment) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("CampaignMycomment", campaignComment);
        showSimpleBack(context, SimpleBackPage.CAMPAIGNCOMMENT_DETAIL, bundle);
    }


    public static void showTesterStat(Context context) {
        showSimpleBack(context, SimpleBackPage.TESTER_STAT);
    }


    public static void testerApply(Context context, TesterStat click, List<TesterStat> tags) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("click", click);
        bundle.putSerializable("pass", (Serializable) tags);
        showSimpleBack(context, SimpleBackPage.TESTER_APPLY, bundle);
    }


    public static void showTesterIndustry(Fragment fragment, String industryId, int requestCode, List<TesterStat> tags) {
        Bundle args = new Bundle();
        args.putString("industryId", industryId);
        args.putSerializable("pass", (Serializable) tags);
        showSimpleBackForResult(fragment, requestCode, SimpleBackPage.TESTER_INDUSTRY, args);
    }

    public static void showCampaignDetail(Context context, String id) {
        Intent intent = new Intent(context, ActiveDetailActivity.class);
        intent.putExtra("campaignid", id);
        intent.putExtra(ActiveDetailActivity.BUNDLE_KEY_PAGE, SimpleBackPage.CAMPAIGNDETAIL.getValue());
        context.startActivity(intent);
    }


}
